var request = {}

layui.define(['user'], function (exports) {

    var user = layui.user;

    request.send = function (url, method = 'GET', data = null, async = true, callback = null) {
        let xhr = new XMLHttpRequest();
        xhr.open(method, url, async);

        xhr.setRequestHeader("Token", user.token());
        xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    if (callback) {
                        var parse = JSON.parse(xhr.responseText);
                        callback(parse.code, parse.message, parse.data);
                    }
                } else {
                    if (callback) {
                        callback(500, 'Request failed with status ' + xhr.status);
                    }
                }
            }
        };

        let sendData = data ? JSON.stringify(data) : null;

        if (async) {
            xhr.send(sendData);
        } else {
            xhr.send(sendData);
            if (xhr.status >= 200 && xhr.status < 300) {
                return JSON.parse(xhr.responseText);
            } else {
                throw new Error('Request failed with status ' + xhr.status);
            }
        }
    }

    request.downloadFile = function (url, filename) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.setRequestHeader("Token", user.token());
      xhr.responseType = "blob"; // 处理二进制数据
      xhr.onload = function () {
        if (xhr.status === 200) {
          var blob = new Blob([xhr.response]); // 创建 Blob
          var link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.download = filename || "downloaded_file";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href); // 释放 URL 对象
        }
      };
      xhr.send();
    }


    exports("request", request);
})